package listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;
import java.util.LinkedList;
import java.util.List;

@WebListener
public class MyListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {

    private ServletContext app = null;

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        HttpSessionAttributeListener.super.attributeAdded(se);
        HttpSessionListener.super.sessionCreated(se);
        @SuppressWarnings("unchecked")
        List<String> online = (List<String>) this.app.getAttribute("online");
        if (se.getValue() != null) {
            online.add((String) se.getValue());
        }
        this.app.setAttribute("online", online);
        this.app.setAttribute("onlineNum", online.size());
        System.out.println("online num" + online.size());
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {
        HttpSessionAttributeListener.super.attributeRemoved(se);
        @SuppressWarnings("unchecked")
        List<String> online = (List<String>) this.app.getAttribute("online");

        String username = (String) se.getValue();
        online.remove(username);

        this.app.setAttribute("online", online);
        this.app.setAttribute("onlineNum", online.size());
        System.out.println("online num" + online.size());
    }


    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContextListener.super.contextInitialized(sce);

        this.app = sce.getServletContext();
        this.app.setAttribute("online", new LinkedList<String>());
        System.out.println("onlineing");

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContextListener.super.contextDestroyed(sce);
    }
}
